'use strict';

module.exports = (req, res, rfun)=>{
    const pubfun = require("../pubfun"), DB = require("../mysql");
    let dv = '[]';
    switch(req.GET.pathname){
        case "/ajax/user":{ //用户列表
            let sql = "SELECT usrid,openid,nickname,regtime,regip,chips,bankchips FROM usr WHERE passporttype='account'";
            let para = [];
            if(req.GET.query.V){
                sql += " AND (usrid = ? OR nickname = ? ) ";
                para.push(req.GET.query.V,req.GET.query.V);
            }
            sql = DB.format(sql, para);
            sql = pubfun.MYPage(sql, "ORDER BY usrid DESC", req.GET.query.P);
            DB.query(sql, (rs)=>{
                dv = {total:rs[1][0].total}
                dv.data = rs[0];
                rfun(dv);
            });
            return;
        }case "/ajax/userdetail":{ //用户明细
            DB.query("SELECT * FROM usr WHERE usrid = ?", (rs)=>{
                dv = {view:""};
                dv.view = `基本信息:
    用户ID：${rs[0].usrid}
    账户：${rs[0].openid}
    登录IP: ${rs[0].loginip}
    手机号: ${rs[0].phone}
    注册IP: ${rs[0].regip}
    注册时间: ${rs[0].regtime}

筹码信息:
    筹码: ${rs[0].chips}
    银行: ${rs[0].bankchips}
`;
                rfun(dv);
            },[req.GET.query.V])
            return;
        }case "/ajax/changepass":{ //修改登录密码
            DB.query("SELECT A.checktoken,A.account FROM account A INNER JOIN usr B ON A.account=B.openid WHERE B.usrid = ?", (rs)=>{
                dv = {m:"修改成功"};
                let ck = rs[0].checktoken.split("/");
                let tm = ck[1].split(" ");
                let np = pubfun.MD5(ck[0] + req.GET.query.P + tm[0])
                DB.query("UPDATE account SET password = ? WHERE account = ?", null, [np, rs[0].account])
                rfun(dv);
            },[req.GET.query.V])
            return;
        }case "/ajax/changebankpass":{ //修改银行密码
            DB.query("UPDATE usr SET bankpassword = ? WHERE usrid = ?", (rs)=>{
                if(rs.affectedRows > 0) dv = {m:"修改成功"};
                rfun(dv);
            }, [req.GET.query.P, req.GET.query.V])
            return;
        }case "/ajax/setbusiness":{ //设置商务用户
            DB.query("UPDATE usrext SET business = ? WHERE usrid = ?",(rs0)=>{
                if(rs0.affectedRows > 0){
                    return rfun({m:"操作成功"});
                }
                DB.query("REPLACE INTO usrext(usrid, business) VALUES(?,?); ", (rs)=>{
                    rfun({m:"操作成功"});
                },[req.GET.query.V,req.GET.query.T])
            },[req.GET.query.T,req.GET.query.V]);
            return;
        }case "/ajax/setrank":{ //设置榜单用户
            DB.query("UPDATE usrext SET ranktype = ? WHERE usrid = ?",(rs0)=>{
                if(rs0.affectedRows > 0){
                    return rfun({m:"操作成功"});
                }
                DB.query("REPLACE INTO usrext(usrid, ranktype) VALUES(?,?); ", (rs)=>{
                    rfun({m:"操作成功"});
                },[req.GET.query.V,req.GET.query.T])                
            },[req.GET.query.T,req.GET.query.V]);        
            return;
        }case "/ajax/bususer":{ //商务用户列表
            if(!req.GET.query.B) req.GET.query.B = pubfun.getdatestr("Y-m-d",0,-7);
            else req.GET.query.B = pubfun.getdatestr("Y-m-d",0,0,new Date(req.GET.query.B));
            if(!req.GET.query.E) req.GET.query.E = pubfun.getdatestr("Y-m-d",0,1);
            else req.GET.query.E = pubfun.getdatestr("Y-m-d",0,1,new Date(req.GET.query.E));
            //console.log(req.GET.query);
            DB.query(`SELECT A.usrid,A.openid,A.nickname,A.chips+A.bankchips Achip,A.chips,A.bankchips,IFNULL(C.ZC,0) ZC,IFNULL(D.ZR,0) ZR,IFNULL(C.ZC,0)-IFNULL(D.ZR,0) LL,A.moneyconsume vip,A.regtime,A.regip FROM usr A 
            INNER JOIN usrext B ON A.usrid=B.usrid 
            LEFT JOIN (SELECT seller,SUM(A.chips) ZC FROM chipstrade A 
                INNER JOIN usr C ON A.buyer = C.usrid AND C.moneyconsume <> 900000000000000
                LEFT JOIN mail B ON A.id=B.relevanceid AND B.attachmenttype = 1 
                WHERE tradetime>=? AND tradetime<? GROUP BY seller) C ON A.usrid=C.seller
            LEFT JOIN (SELECT buyer,SUM(A.chips) ZR FROM chipstrade A 
                INNER JOIN usr C ON A.seller = C.usrid AND C.moneyconsume <> 900000000000000
                LEFT JOIN mail B ON A.id=B.relevanceid AND B.attachmenttype = 1
                WHERE (isgetattachment=1 OR isgetattachment IS NULL) AND tradetime>=? AND tradetime<? GROUP BY buyer) D ON A.usrid=D.buyer
            WHERE business=?`, (rs)=>{
                const cfg = require("./cfg");
                for(let i=0;i<rs.length;i++){
                    let v = 0;
                    for(;v < cfg.vip.length;v++){
                        if(rs[i].vip < cfg.vip[v]) break;
                    }
                    if(v == 13) rs[i].vip = "商人";
                    else if(v == 0) rs[i].vip = "非VIP";
                    else rs[i].vip = "VIP"+v;
                }
                rfun(rs);
            },[req.GET.query.B,req.GET.query.E,req.GET.query.B,req.GET.query.E,req.GET.query.T])
            return;
        }case "/ajax/rankuser":{ //榜单用户列表
            DB.query(`SELECT A.usrid,A.openid,A.nickname,A.chips+A.bankchips Achip,A.chips,A.bankchips,A.moneyconsume vip,A.regtime,A.regip FROM usr A 
            INNER JOIN usrext B ON A.usrid=B.usrid 
            WHERE ranktype=1`, (rs)=>{
                const cfg = require("./cfg");
                for(let i=0;i<rs.length;i++){
                    let v = 0;
                    for(;v < cfg.vip.length;v++){
                        if(rs[i].vip < cfg.vip[v]) break;
                    }
                    if(v == 13) rs[i].vip = "商人";
                    else if(v == 0) rs[i].vip = "非VIP";
                    else rs[i].vip = "VIP"+v;
                }
                rfun(rs);
            },[req.GET.query.B,req.GET.query.E,req.GET.query.B,req.GET.query.E,req.GET.query.T])
            return;
        }case "/ajax/rebatetype":{ //返利类型列表
            let sql = "SELECT *,CASE groupid WHEN 0 THEN '日销量' ELSE '10日销量' END groupname FROM rebateType";
            if(req.GET.query.M) sql = "SELECT tid,typename FROM rebateType";
            DB.query(sql,(rs)=>{
                rfun(rs);
            })
            return;
        }case "/ajax/rebateadd":{ //返利类型添加
            DB.query("INSERT INTO rebateType(tid,typename,groupid,BL) VALUES(?,?,?,?)",(rs)=>{
                dv = {m:"添加成功"}
                if(rs.affectedRows != 1) dv.m = "出错了";
                rfun(dv);
            },[req.GET.query.ti,req.GET.query.tn,req.GET.query.gi,req.GET.query.bl])
            return;
        }case "/ajax/rebatedel":{ //返利类型删除
            DB.query("DELETE FROM rebateType WHERE find_in_set(tid,?)",(rs)=>{
                dv = {m:"删除成功"};
                if(rs.affectedRows < 1) dv.m = "出错了";
                rfun(dv);
            },[req.GET.query.ids])
            return;
        }case "/ajax/rebatesend":{ //返利发放
            if(req.GET.query.U){ //发放返利
                dv = {m:"发放结果<br/>"};
                DB.query("SELECT typename,groupid,BL FROM rebateType WHERE tid = ?",(rs)=>{
                    if(rs.length == 0){
                        dv.m += "奖励类型错误";
                        rfun(dv);
                        return;
                    }
                    let ul = req.GET.query.U.replace("\r", "").split("\n");
                    let runRd = function(ind){
                        if(ind >= ul.length){
                            return rfun(dv);
                        }
                        DB.query("SELECT usrid FROM usr Where usrid = ?", (rs1)=>{
                            if(rs1.length < 1){
                                dv.m += "\n" + ul[ind] + " 未找到"
                                return runRd(ind + 1);
                            }
                            DB.query("SELECT rid FROM rebateRecord WHERE tid = ? AND TO_DAYS(times) = TO_DAYS(NOW()) AND usrid = ?",(rs2)=>{
                                if(rs2.length > 0){
                                    dv.m += "\n" + ul[ind] + " " + rs[0].typename + " 已经发送过了";
                                    return runRd(ind + 1);
                                }

                                let sql = "", para = [];
                                if(rs[0].groupid == 0){ //日销奖励
                                    sql = `SELECT SUM(A.chips) score FROM chipstrade A 
                                    INNER JOIN usr B ON A.buyer = B.usrid AND moneyconsume <> 900000000000000 
                                    LEFT JOIN mail C ON A.id = C.relevanceid AND C.attachmenttype = 1
                                    WHERE seller = ? AND (C.isgetattachment = 1 OR C.isgetattachment IS NULL) AND TO_DAYS(tradetime) = TO_DAYS(NOW()) - 1`;
                                    para.push(ul[ind]);
                                }else{ //10日净销
                                    sql = `SELECT SUM(CASE WHEN A.seller = ? THEN A.chips ELSE 0 END - CASE WHEN A.buyer = ? THEN A.chips ELSE 0 END) score FROM chipstrade A 
                                    INNER JOIN usr B ON A.buyer = B.usrid 
                                    INNER JOIN usr C ON A.seller = C.usrid 
                                    LEFT JOIN mail D ON A.id = D.relevanceid AND C.attachmenttype = 1
                                    WHERE ((A.seller = ? AND B.moneyconsume <> 900000000000000) OR (A.buyer = ? AND C.moneyconsume <> 900000000000000)) AND (isgetattachment = 1 OR isgetattachment IS NULL) AND tradetime >= ? AND tradetime < ? `;
                                    para = [ul[ind],ul[ind],ul[ind],ul[ind]];
                                    let endstr = pubfun.getdatestr("Y-m-d"), begstr = "";
                                    let dt = new Date();
                                    if(dt.getDate() == 1){
                                        begstr = pubfun.getdatestr("Y-m-d",-1,20);
                                    }else if(dt.getDate() == 11 || dt.getDate() == 21){
                                        begstr = pubfun.getdatestr("Y-m-d",0,-10);
                                    }else{
                                        dv.m += "\n" + ul[ind] + " " + rs[0].typename + " 今天不能发生";
                                        return runRd(ind + 1);
                                    }
                                    para.push(begstr, endstr);
                                }
                                DB.query(sql, (rs3)=>{
                                    if(rs3.length == 0 || rs3[0].score * rs[0].BL / 100 < 1){
                                        dv.m += "\n" + ul[ind] + " 可发送奖励小于1";
                                        return runRd(ind + 1);
                                    }
                                    /*DB.query("INSERT INTO mail(id,sendername,senderid,receiverid,title,content,attachmenttype,attachmentnum,isread,mailtype,isgetattachment,relevanceid,lasttime) SELECT (SELECT MAX(id) FROM mail),'System',1000,?,?,?,1,?,0,0,0,0,?",(rs4)=>{
                                        if(rs4.affectedRows > 0){
                                            dv.m += "\n" + ul[ind] + " 发送奖励"+parseInt(rs3[0].score * rs[0].BL / 100)+"成功";
                                        }else{
                                            dv.m += "\n" + ul[ind] + " 发送奖励出问题了";
                                        }
                                        runRd(ind + 1);
                                    },[ul[ind],rs[0].typename,"奖励",rs3[0].score * rs[0].BL / 100,parseInt(Date.now())])*/
                                    DB.query("INSERT INTO rebateRecord(`tid`,`score`,`usrid`,`times`,`sm`,`opname`,`Status`) VALUES(?,?,?,NOW(),?,?,0)",(rs4)=>{
                                        if(rs4.affectedRows > 0){
                                            dv.m += "\n" + ul[ind] + " 发送奖励"+parseInt(rs3[0].score * rs[0].BL / 100)+"成功";
                                        }else{
                                            dv.m += "\n" + ul[ind] + " 发送奖励出问题了";
                                        }
                                        runRd(ind + 1);
                                    },[req.GET.query.tid, rs3[0].score * rs[0].BL / 100, ul[ind], req.GET.query.bz, req.SESSION.N])
                                }, para);
                            },[req.GET.query.tid, ul[ind]])
                        }, [ul[ind]]);
                    }
                    runRd(0);
                },[req.GET.query.tid])
            }else{ //返利信息查询
                let sql = "", para = [];
                if(req.GET.query.T){ //查询明细
                    sql = `SELECT times,A.usrid,C.nickname,typename,score,sm BZ FROM rebateRecord A 
                    INNER JOIN rebateType B ON A.tid=B.tid 
                    INNER JOIN usr C ON A.usrid=C.usrid
                    WHERE A.tid = ? AND CAST(times AS DATE) = ?`;
                    para = [req.GET.query.T,req.GET.query.B]
                }else{
                    if(!req.GET.query.B) req.GET.query.B = pubfun.getdatestr("Y-m-d");
                    req.GET.query.E = pubfun.getdatestr("Y-m-d",0,1,req.GET.query.E);
                    sql = "SELECT CAST(times AS DATE) dt,A.tid,typename,sum(score) ss,opname FROM rebateRecord A INNER JOIN rebateType B ON A.tid=B.tid WHERE times >= ? AND times < ? GROUP BY CAST(times AS DATE),A.tid,typename,opname";
                    para = [req.GET.query.B,req.GET.query.E]
                }
                DB.query(sql,(rs)=>{
                    rfun(rs);
                },para);
            }
            return;
        }case "/ajax/chargecode":{ //体检卡
            if(req.GET.query.a == "del"){
                DB.query("DELETE FROM activationcode WHERE batch = ? AND (SELECT SUM(usedcnt) FROM activationcode WHERE batch = ?) = 0",(rs)=>{
                    rfun(dv);
                }, [req.GET.query.batch, req.GET.query.batch])
            }else if(req.GET.query.batch){ //导出
                DB.query("SELECT `key`,chips FROM activationcode WHERE batch = ?",(rs)=>{
                    let dv = {view:""};
                    for(let i=0;i<rs.length;i++){
                        dv.view += rs[i].key + "," + rs[i].chips + "\n";
                    }
                    res.writeHead(200, {
                        'Content-Type': 'application/octet-stream',//告诉浏览器这是一个二进制文件
                        'Content-Disposition': 'attachment; filename=out.csv',//告诉浏览器这是一个需要下载的文件
                    });
                    res.end(dv.view);
                    rfun(false);
                    //rfun(dv);
                },[req.GET.query.batch])
            }else if(req.GET.query.N){ //生成体检卡
                dv = {m:""};
                let lt = parseInt((new Date(req.GET.query.T).getTime() - Date.now())/1000);
                if(!(req.GET.query.N > 0)){
                    dv.m = "数量必须大于0";
                }
                if(!(req.GET.query.C > 0)){
                    dv.m = "游戏币必须大于0";
                }
                if(!(lt > 300)){
                    dv.m = "有效时间必须正确";
                }
                //console.log(dv)
                if(dv.m != ""){
                    return rfun(dv);
                }
                DB.query(`SET @创建key个数=?,@筹码=?,@钻石=0,@领取次数=1,@过期时长=?, @批次头=?, @批次=0,@批次限制=1,@监控次数=1;
                CALL CreateActivationCode(@创建key个数,@筹码,@钻石,@领取次数,@过期时长, @批次头, @批次,@批次限制,@监控次数);`,(rs)=>{
                    //console.log(rs)
                    if(rs[1].affectedRows > 0){
                        dv.m = "生成成功";
                    }
                    rfun(dv);
                },[req.GET.query.N,req.GET.query.C,lt,req.GET.query.B])
            }else{ //查询体检卡信息
                if(!req.GET.query.B) req.GET.query.B = pubfun.getdatestr("Y-m-d");
                req.GET.query.E = pubfun.getdatestr("Y-m-d",0,1,req.GET.query.E);
                DB.query("SELECT CAST(MIN(create_time) AS DATE) dt,batch,chips,COUNT(*) num,SUM(usedcnt) usenum FROM activationcode GROUP BY batch,chips ORDER BY batch DESC",(rs)=>{
                    rfun(rs);
                })
            }
            return;
        }case "/ajax/useronline":{ //在线玩家
            const rm = {1:"大厅",2:"百家乐",3:"黑杰克",4:"水果机",5:"百人牛牛",6:"红黑大战",7:"翻牌机",8:"捕鱼",9:"德州",10:"捕鱼2"}
            DB.query("SELECT `online_id` FROM `poker`.`online_usr` ORDER BY `id` DESC LIMIT 1",(rs1)=>{
                DB.query(`SELECT A.usrid,nickname,A.chips,bankchips,IFNULL(SUM(B.chips),0) win,online,regip
                FROM usr A 
                LEFT JOIN moneytrans B ON A.usrid = B.usrid AND TO_DAYS(B.times) = TO_DAYS(now()) AND transtype in('百家乐下注改变扣钱','百家乐下注改变加钱','30线老虎机筹码变化','1线老虎机筹码变化','9线老虎机筹码变化','德州牛仔下注','德州牛仔下注扣钱','德州牛仔手牌下注加钱','德州牛仔贏牌下注加钱','翻牌机改变扣钱','翻牌机改变加钱','翻牌机改变','21点下注改变扣钱','21点下注改变加钱','红黑大战下注扣钱','红黑大战下注加钱','德州牛仔普通下注加钱','玩家海王改变','玩家捕鱼改变','百家乐退钱','红黑大战下注','翻牌机退钱','百人牛牛扣钱','百人牛牛加钱','百人牛牛庄家加钱','百人牛牛奖池大奖')
                WHERE online > 0 AND A.usrid IN(${rs1[0].online_id})
                GROUP BY A.usrid,nickname,A.chips,bankchips,online`,(rs)=>{
                    for(let i=0;i<rs.length;i++){
                        rs[i].online = rm[rs[i].online] || rs[i].online;
                    }
                    rfun({view:"在线人数: " + rs.length, data:rs});
                });
            })
            return;
        }case "/ajax/tradelog":{ //转账记录
            let sql = `SELECT A.id,seller,sellername,buyer,buyername,chips,tradetime,CASE WHEN B.id IS NULL OR B.isgetattachment=1 THEN 9 ELSE stat END stat FROM chipstrade A 
            LEFT JOIN mail B ON A.id = B.relevanceid`;
            sql = pubfun.MYPage(sql, "ORDER BY A.id DESC", req.GET.query.P);
            DB.query(sql, (rs)=>{
                dv = {total:rs[1][0].total}
                dv.data = rs[0];
                rfun(dv);
            });
            return;
        }case "/ajax/tradedeal":{ //转账处理
            DB.query("UPDATE chipstrade SET stat = ? WHERE id = ? AND stat = 0", (rs)=>{
                rfun(dv);
                DB.query("DELETE FROM mail WHERE id = (SELECT id FROM mail WHERE senderid = 1000 AND attachmentnum = 0 AND relevanceid = (SELECT id FROM mail WHERE attachmentnum > 0 AND relevanceid = ?))", null, [req.GET.query.id])
            },[req.GET.query.T, req.GET.query.id])
            return;
        }
    }
    rfun(dv);
}